<template>
	<view class="container">
		<image class="fullw" :src="dataList[cindex].src" :show-menu-by-longpress="cindex!=1" lazy-load mode="widthFix">
		</image>
		<view v-if="curType=='1001'" class="full_btn nbg fixed">
			<button class="mbtn" @click="drawPoster(dataList[0].src)">
				分享
			</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import { onLoad, onShareAppMessage, onUnload } from '@dcloudio/uni-app';
	import { takeSaveShare } from '@/utils/public'
	import { env } from '@/api/env.js'
	import mapi from '@/utils/mapi'
	import { mnavTo, showLoading, hideLoading } from '@/utils/helper';
	import { shareinfoGift } from '@/api/vmeitime-http/index.js';
	import { useShopStore } from '@/stores/shopStore';
	const shopStore = useShopStore();
	const nsell_member_id = ref('') //门店ID
	const saveQrPath = ref() //保存小程序码文件目录
	const tempFilePath = ref()
	const share_id = ref()
	const dataList = ref([
		{
			name: '邀请有礼',
			type: '1001',
			src: ''
		},
		{
			name: '品牌故事',
			type: '1002',
			src: env.FileUrl + 'food/images/brand_img0001.png'
		},
		{
			name: '健康顾问',
			type: '1003',
			src: env.FileUrl + 'food/images/brand_img02.png'
		}
	])
	const cindex = ref(1)
	const curType = ref('')
	onUnload(() => {
		saveQrPath.value && getRemoveSavedFile(saveQrPath.value)
	})
	onLoad((options) => {
		
		let choseStore = uni.getStorageSync('lastSelectedItem');//选择的门店
		nsell_member_id.value = choseStore.nmember_id
		console.log('nsell_member_id.value---------------------门店id', nsell_member_id.value)
		curType.value = options.type || '1002';
		cindex.value = dataList.value.findIndex(item => item.type == curType.value)
		let citem = dataList.value[cindex.value] || {};
		
		getshareId();
		uni.setNavigationBarTitle({
			title: citem.name || ''
		})
	})
	console.log('env', env);

	// 分享好友
	onShareAppMessage(() => {
		return new Promise(async (resolve, reject) => {
			// let param = {
			// 	event_id: '40', //事件id  1:会员注册, 2:H5分享， 3:商品价格标签, 4:商品超链接分享, 5:拼团， 6:线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
			// 	source_type: '1', //1首页分享，2商品分享，3名片分享，4商品超链接分享5拼团,6线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
			// 	goods_id: '',
			// 	goods_sku: '',
			// 	activity_id: '',
			// 	sell_member_id: nsell_member_id.value, //门店id
			// 	// buy_member_id: paramData.buy_member_id || '', //用户id
			// }
			const shareTits=uni.getStorageSync('shareTitles')
			try {
				// let shareId = await takeSaveShare(param)
				if (share_id.value) {
					const imageUrl = uni.getStorageSync('shareImg')
					let msg = {
						title: curType.value=='1001'&&shareTits ? shareTits:'好食材 健康外卖',
						content:'好食材 健康外卖',
						path: '/pages/index/home/home?scene=' + share_id.value,
						imageUrl: imageUrl||'https://cdn-static.yekjx.com/resouces/daiyan/xyyy_share.png',
					}
					resolve(msg)
				} else {
					reject('');
					mapi.msg('分享失败,请稍后重试')
				}
			} catch (e) {
				reject('');
				mapi.msg('分享失败,请稍后重试')
				console.error(e)
				//TODO handle the exception
			}

		});
	});

	const getshareId = async () => {
		let param = {
			event_id: '40', //事件id  1:会员注册, 2:H5分享， 3:商品价格标签, 4:商品超链接分享, 5:拼团， 6:线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
			source_type: '1', //1首页分享，2商品分享，3名片分享，4商品超链接分享5拼团,6线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
			goods_id: '',
			goods_sku: '',
			activity_id: '',
			sell_member_id: shopStore.curSellerMemberId|| '', //门店id
			// buy_member_id: paramData.buy_member_id || '', //用户id
		}
		try {
			// showLoading()
      console.log('分享参数-------------------------',param)
			let shareId = await takeSaveShare(param)
			if (shareId) {
				share_id.value = shareId
				console.log('分享idshare_idssssss--------------------------------', share_id.value)
				hideLoading();
				// total_money_num.value = res.object || 0
				if(curType.value=='1001'){
					 shareinfoGiftList();
				}
     
			}
		} catch (e) {
			console.error('用户信息', e)
			hideLoading();
			mapi.msg('网络繁忙，请稍后再试!');
		}
	}

	const getRemoveSavedFile = (filePath : any) => {
		wx.getFileSystemManager().unlinkSync(filePath);
		console.log('unlink删除成功：' + filePath);
	}
	const toRandom = (lower : any, upper : any) => {
		return Math.floor(Math.random() * (upper - lower + 1)) + lower;
	}
	const drawPoster = async (xcxShareQr : any) => {
		await getCodeImagePath(xcxShareQr); //存到本地会带http，组件认成网络图片进行下载。。。
	}
	const getCodeImagePath = (base64data : any) => {
		return new Promise(async (resolve, reject) => {
			const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
			if (!format) {
				reject(new Error('ERROR_BASE64SRC_PARSE'));
			}
			const filePath = `${wx.env.USER_DATA_PATH}/${'tmp_base64src'}.${format}` + toRandom(1, 9999999999)
			// console.log('filePath', filePath);
			saveQrPath.value = filePath;
			tempFilePath.value = filePath;
			const buffer = uni.base64ToArrayBuffer(bodyData);
			uni.getFileSystemManager().writeFile({
				filePath,
				data: buffer,
				encoding: 'binary',
				success(res) {
					wx.showShareImageMenu({ path: filePath });
					resolve(filePath);
					// console.log('filePath-----------------------',filePath)
				},
				fail(e) {
					console.log(e);
					reject(new Error('ERROR_BASE64SRC_WRITE'));
				}
			});
		});
	}
	const shareinfoGiftList = async () => {
		try {
			// showLoading()
			let res = await shareinfoGift({
				path: 'pages/index/home/home',
				shareId:share_id.value
			})
			if (res) {
				// hideLoading();
				// total_money_num.value = res.object || 0
				const xcxShareQr = 'data:image/png;base64,' + uni.arrayBufferToBase64(res);
				// console.log('xcxShareQr-----------------------------分享有礼的图片',xcxShareQr)
				dataList.value[0].src = xcxShareQr
				// drawPoster(xcxShareQr)
			}
		} catch (e) {
			console.error('分享有礼错误', e)
			hideLoading();
			mapi.msg('网络繁忙，请稍后再试!');
		}
	}
</script>

<style lang="scss">
	.fullw {
		height: 100vh;
	}
</style>